/**
 * Created by Toma on 2016/11/29.
 * 爬虫
 */

var http = require('http');
var cheerio = require('cheerio');
var url = 'http://www.imooc.com/learn/348';

function fillterChapters(html) {
  var $ = cheerio.load(html);
  var chapters = $('.chapter');
  var courseData = [];

  chapters.each(function (item) {
    var chapter = $(this)
    var chapterTitile = chapter.find('strong').text();
    var videos = chapter.find('.video').children('li');
    var chapterData = {
      chapterTitle: chapterTitile,
      videos: []
    }
    videos.each(function (item) {
      var _this = $(this);
      var videoTitle = $(this).text();
      var id = _this.find('a').attr('href').split('video/')[1];
      chapterData.videos.push({
        id: id,
        title: videoTitle
      });
    });

    courseData.push(chapterData);
  });

  return courseData;
}

function printCourseInfo(courseData) {
  courseData.forEach(function (item) {
    var chapterTitle = item.chapterTitle;
    console.log(chapterTitle.trim() + '\n');
    item.videos.forEach(function (video) {
      console.log('  [' + video.id.trim() + '] ' + video.title.trim() + '\n');
    });
  });
}

http.get(url, function (res) {
  var html = '';
  res.on('data', function (data) {
    html += data;
  });
  res.on('end', function () {
    var courseData = fillterChapters(html);
    printCourseInfo(courseData);
  });
}).on('error', function () {
  console.log('出错了————');
});